#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

install_specs=${CONFIG_ROOT}/ohos-cross/aarch64-pkgs.toml

parse_specs_from_dry_run() {
    local tmp_pkgs_root=$1
    local dry_run_output=$(PKGS_ROOT=${tmp_pkgs_root} ferrium install --dry-run ${install_specs})

    local specs=()
    local in_tasks=false
    while read -r line; do
        if [[ $line == "Tasks:" ]]; then
            in_tasks=true
        elif $in_tasks; then
            if [[ $line != *"-"* ]]; then
                in_tasks=false
                break
            fi
            eval "$(echo "$line" | awk -F', ' '{
                for(i=1; i<=NF; i++) {
                    if($i ~ /spec:/) {gsub(/spec: /, "", $i); printf "spec=%s; ", $i}
                }
            }')"
            specs+=(${spec})
        fi
    done <<< "$dry_run_output"

    echo "${specs[@]}"
}

tmp_pkgs_root=$(mktemp -d)
specs=$(parse_specs_from_dry_run ${tmp_pkgs_root})

# Reuse built packages
echo "Reusing built packages"
for spec in ${specs[@]}; do
    if [ -f /pkg/${spec}.stat ] && [ ! -f ${tmp_pkgs_root}/${spec}.stat ]; then
        echo "Reusing ${spec}"
        cp -lrP /pkg/${spec} ${tmp_pkgs_root}/${spec}
	if [ $? -eq 0 ]; then
            ln -f /pkg/${spec}.stat ${tmp_pkgs_root}/${spec}.stat
	fi
    fi
done

# Build missing packages
echo "Building missing packages"
PKGS_ROOT=${tmp_pkgs_root} ferrium install ${install_specs} || exit 1

# Replace pkgs root
echo "Replacing pkgs root"
rm -rf /pkg/* || exit 1
mv ${tmp_pkgs_root}/* /pkg/ || exit 1

rm -r ${tmp_pkgsgroot}
